from flask import Blueprint, request, jsonify,redirect
import json
from db import db1
from .admin_user import get_data
from flask import current_app as app
from flask_mail import Mail,Message
from werkzeug.security import check_password_hash,generate_password_hash

bp_user = Blueprint('user', __name__)

def send_email(title,email,content):
    mail = Mail(app)
    msg = Message(title, sender='ztlman12@163.com', recipients=[email])  # 发件人，收件人
    msg.html = content
    mail.send(msg)


@bp_user.route('/regi', methods=['POST'])
def regi():
    if request.method == 'POST':
        data = get_data()
        sql1 = '''select id from users where email = "%s" '''%(data['email'])
        res = db1.findone(sql1)
        if res:
            return jsonify({'code':20010,'mes':用户已存在})
        sql2 = '''insert into users values(0,"%s","%s",%d,"%s",%d)''' % (
        data['username'], generate_password_hash(data['password']),0,  data['email'],0)
        print(sql2)
        db1.update(sql2)
        send_email('欢迎使用实验楼',data['email'],"欢迎使用，点击以下<a href='http://localhost:5000/users/validEmail?email="+data['email']+"'>链接</a>验证")
        return jsonify({'code': 200})

@bp_user.route('/validEmail')
def validEmail():
    email = request.args.get('email')
    sql ='''update users set status = 1 where email = "%s" '''%(email)
    db1.update(sql)
    return redirect('http://localhost:8888')
